<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            height: 300px;
            overflow: auto;
        }
        .observe-me{
            height: 200px;
            width: 50px;
            background-color: lightblue;
            text-align: center;
            line-height: 200px;
            font-size: 16px;
        }
        .other{
            height: 300px;
            background-color: pink;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="observe-me">要监听的元素</div>
        <div class="other">其他元素</div>
    </div>
</body>
<script>
    // 创建观察器
    // IntersectionObserver 用于监听元素的出现和消失
    // ResizeObserver 用于监听元素的尺寸变化
const observerIsHide = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      console.log('元素出现', entry.target);
    } else {
      console.log('元素消失', entry.target);
    }
  });
}, {
  threshold: 1 // 交叉比例阈值
});
// 创建监听元素尺寸的观察器
const resizeObserver = new ResizeObserver(entries => {
    for (const entry of entries) {
        console.log(entry,9999);
        
    }
});

// 开始观察目标元素
const target = document.querySelector('.observe-me');
const other = document.querySelector('.other');
const box = document.querySelector('.box');

observerIsHide.observe(target);
resizeObserver.observe(other);
// resizeObserver.disconnect(); // 停止监听尺寸变化
// observer.disconnect(); // 停止监听元素出现和消失

// 监听dom属性变化:删除、添加子节点、属性变化
const observerDomChange = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
     //mutation.attributes属性变化
    //  不管是当前节点的属性变化，还是子节点的属性变化，都会触发attributes
    if (mutation.type === 'attributes') {
      console.log('属性发生变化',mutation);
    }
    if (mutation.type === 'childList') {
      console.log('子节点发生变化',mutation);
      // 新增的节点通过addedNodes属性获取
      mutation.addedNodes.forEach(node => {
        console.log('新增的节点:', node);
      });
      // 删除的节点通过removedNodes属性获取
      mutation.removedNodes.forEach(node => {
        console.log('删除的节点:', node);
      });
    }
  });
});
setTimeout(() => {
   box.classList.add('new-class');
   let newDiv = document.createElement('div');
   newDiv.innerText = '新增的节点';
   box.appendChild(newDiv);
   newDiv.classList.add('temp-div');
}, 2000);

observerDomChange.observe(box, {
  childList: true,
  attributes: true,
  subtree: true
});

document.fonts.ready.then(() => {
  console.log('所有字体加载完成');
});

document.fonts.addEventListener('loading', (event) => {
  console.log('字体开始加载:', event.fontface.family);
});
</script>
</html>